package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: SGS
 * @Date : 2020/12/1 17:42
 * @Version :
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    private final UserClient userClient;
    private final JwtUtils jwtUtils;

    public UserAuthServiceImpl(UserClient userClient, JwtUtils jwtUtils) {
        this.userClient = userClient;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //授权中心携带用户密码,到用户中心查询用户
            UserDTO user = userClient.queryUserByPhoneAndPassword(username, password);
            //校验查询结果
            if (user == null){
                throw new LyException(400,"用户或者密码错误");
            }
            //如果正确生成jwt凭证,查询错误则返回400
            //准备用户信息
            UserDetails userDetails = UserDetails.of(user.getId(), user.getUsername());
            //生成jwt
            String jwt = jwtUtils.createJwt(userDetails);
            //jwt写入cookie
            writeCookie(response,jwt);
        } catch (FeignException e) {
            //把远程调用异常转换抛出
            throw new LyException(e.status(),e.contentUTF8());
        }

    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, jwt);
        //cookie作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        //是否禁止JS操作cookie,避免XSS攻击
        cookie.setHttpOnly(true);
        //cookie有效期,-1就是跟随当前会话,浏览器关闭就消失
        cookie.setMaxAge(-1);
        //cookie的作用路径, / 代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
